package com.xjiye_test.payServer.servletGroup.weixin;

import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.db.Entity;
import com.xiaoleilu.hutool.db.Page;
import com.xiaoleilu.hutool.db.PageResult;
import com.xiaoleilu.hutool.log.StaticLog;
import com.xiaoleilu.hutool.util.NumberUtil;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xjiye_test.payServer.dao.OrderDao;
import com.xjiye_test.payServer.serverletUtil.*;
import com.xjiye_test.payServer.servletGroup.shemmapay.GlobalVariable;
import com.xjiye_test.payServer.servletGroup.shemmapay.TestParser;
import org.xml.sax.SAXException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/6/7.
 */
public class WeixinDownloadBill extends HttpServlet {

    int testPayShort; //支付短款订单数控制
    int testPayLong; //支付长款订单数控制
    int testRefundShort; //退款短款订单数控制
    int testRefundLong; //退款长款订单数控制
    int testAmount;//金额出错订单数控制

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        testPayShort=0;
        testPayLong=0;
        testRefundShort=0;
        testRefundLong=0;
        testAmount=0;
        StaticLog.info("进入下载对账单方法");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type","text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String reStr=null;
        //处理请求
        //读取要下载的文件
        req.setCharacterEncoding("UTF-8");
        int size = req.getContentLength();
        InputStream is = req.getInputStream();
        try {
            Map mapRequest = XMLParser.getMapFromXML(new String(ReadBytes.readBytes(is, size)));
            OrderDao orderdao=new OrderDao();
            List<String> keys= new ArrayList<>();
            List<String> values= new ArrayList<>();
            keys.add("appid=");
            values.add(mapRequest.get("appid").toString());
            keys.add("suppId=");
            values.add(mapRequest.get("mch_id").toString());
            keys.add("time>=");
            values.add(DateUtil.parse(mapRequest.get("bill_date").toString()+" 00:00:00", "yyyyMMdd HH:mm:ss")+"");
            keys.add("time<=");
            values.add(DateUtil.parse(mapRequest.get("bill_date").toString()+" 23:59:59", "yyyyMMdd HH:mm:ss")+"");
            PageResult<Entity> orders=orderdao.getDataByCondition(new Page(0,10000),keys,values);
            reStr="交易时间,公众账号ID,商户号,子商户号,设备号,微信订单号,商户订单号,用户标识,交易类型,交易状态,付款银行,货币种类,总金额,企业红包金额,微信退款单号,商户退款单号,退款金额,企业红包退款金额,退款类型,退款状态,商品名称,商户数据包,手续费,费率\r\n";
            int totalOrderAmount=0;
            int totalRefundAmount=0;
            int[] orderTest= TestParser.getOrderTest(GlobalVariable.test);
            int totalOrder=orders.size();
            for(Entity order:orders){
                if(orderTest[0]==0){
                    if(!order.getStr("paystatus").equals("REFUND")){
                        if(testPayShort<2){
                            testPayShort++;
                            StaticLog.error("测试渠道少支付订单：订单号 " +order.getStr("suppOrderNo"));
                            totalOrder--;
                            continue;
                        }
                    }
                }
                if(orderTest[1]==0){
                    if(order.getStr("paystatus").equals("REFUND")){
                        if(testRefundShort<2){
                            testRefundShort++;
                            StaticLog.error("测试渠道少退款订单：订单号 " +order.getStr("suppOrderNo"));
                            totalOrder--;
                            continue;
                        }
                    }
                }
                int newAmount=NumberUtil.generateRandomNumber(1,999999,1)[0];
                if(orderTest[0]==3){
                    if(!order.getStr("paystatus").equals("REFUND")){
                        if(testAmount<2){
                            testAmount++;
                            StaticLog.error("测试渠道支付订单金额错误：订单号 " +order.getStr("suppOrderNo") +" 少了"+NumberUtil.mul(order.getInt("amount")-newAmount,0.01) );
                            order.set("amount",newAmount);
                        }
                    }
                }
                if(orderTest[1]==3){
                    if(order.getStr("paystatus").equals("REFUND")){
                        if(testAmount<2){
                            testAmount++;
                            StaticLog.error("测试渠道退款订单金额错误：订单号 " +order.getStr("suppOrderNo") +" 少了"+NumberUtil.mul(order.getInt("amount")-newAmount,0.01) );
                            order.set("refundAmount",newAmount);
                        }
                    }
                }
                totalOrderAmount+=order.getInt("amount");
                totalRefundAmount+=order.getInt("refundAmount");
                reStr+=getWeiXinBillOrder(order);
            }
            if(orderTest[0]==2){
                for(int i=0;i<2;i++){
                    totalOrder++;
                    Entity order=new Entity();
                    int amount=NumberUtil.generateRandomNumber(1,999999,1)[0];
                    order.set("time",DateUtil.parse(mapRequest.get("bill_date").toString()+" 13:23:23", "yyyyMMdd HH:mm:ss"));
                    order.set("appid",mapRequest.get("appid"));
                    order.set("suppId",mapRequest.get("mch_id"));
                    order.set("wechatOrderNo",IdWorker.getIdWorker().nextId());
                    order.set("suppOrderNo",IdWorker.getIdWorker().nextId());
                    order.set("openid",RandomUtil.randomString(29));
                    order.set("paytype","MICROPAY");
                    order.set("paystatus","SUCCESS");
                    order.set("amount",amount);
                    order.set("wechatRefundNo","");
                    order.set("suppRefundNo","");
                    order.set("refundAmount",0);
                    order.set("feeAmount",(new Double(NumberUtil.round(NumberUtil.mul(amount/100.00,0.003),0))).intValue());
                    order.set("fee",3);
                    totalOrderAmount+=order.getInt("amount");
                    totalRefundAmount+=order.getInt("refundAmount");
                    StaticLog.error("测试渠道多支付订单：订单号 " +order.getStr("suppOrderNo"));
                    reStr+=getWeiXinBillOrder(order);
                }
            }
            if(orderTest[1]==2){
                for(int i=0;i<2;i++){
                    totalOrder++;
                    Entity order=new Entity();
                    int amount=NumberUtil.generateRandomNumber(1,999999,1)[0];
                    order.set("time",DateUtil.parse(mapRequest.get("bill_date").toString()+" 13:23:23", "yyyyMMdd HH:mm:ss"));
                    order.set("appid",mapRequest.get("appid"));
                    order.set("suppId",mapRequest.get("mch_id"));
                    order.set("wechatOrderNo",IdWorker.getIdWorker().nextId());
                    order.set("suppOrderNo",IdWorker.getIdWorker().nextId());
                    order.set("openid",RandomUtil.randomString(29));
                    order.set("paytype","MICROPAY");
                    order.set("paystatus","REFUND");
                    order.set("amount",0);
                    order.set("wechatRefundNo",IdWorker.getIdWorker().nextId());
                    order.set("suppRefundNo",IdWorker.getIdWorker().nextId());
                    order.set("refundAmount",amount);
                    order.set("feeAmount",0);
                    order.set("fee",0);
                    totalOrderAmount+=order.getInt("amount");
                    totalRefundAmount+=order.getInt("refundAmount");
                    StaticLog.error("测试渠道多退款订单：订单号 " +order.getStr("suppOrderNo"));
                    reStr+=getWeiXinBillOrder(order);
                }
            }
            reStr+="总交易单数,总交易额,总退款金额,总企业红包退款金额,手续费总金额\r\n";
            reStr+="`"+totalOrder+",`"+NumberUtil.mul(totalOrderAmount,0.01)+",`"+NumberUtil.mul(totalRefundAmount,0.01)+",`0.00,`0.00000\r\n";
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            out.print(reStr);
            out.flush();
        }
    }

    public String getWeiXinBillOrder(Entity order){
        String reStr="";
        reStr+="`"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getDate("time"));//交易时间
        reStr+=",`"+order.getStr("appid");//公众账号ID
        reStr+=",`"+order.getStr("suppId");//商户号
        reStr+=",`0";//子商户号
        reStr+=",`";//设备号
        reStr+=",`"+order.getStr("wechatOrderNo");//微信订单号
        reStr+=",`"+order.getStr("suppOrderNo");//商户订单号
        reStr+=",`"+order.getStr("openid");//用户标识
        reStr+=",`"+order.getStr("paytype");//交易类型
        reStr+=",`"+order.getStr("paystatus");//交易状态
        reStr+=",`CFT";//付款银行
        reStr+=",`CNY";//货币种类
        reStr+=",`"+ NumberUtil.mul(order.getInt("amount"),0.01);//总金额
        reStr+=",`0.00";//企业红包金额
        reStr+=",`"+order.getStr("wechatRefundNo");//微信退款单号
        reStr+=",`"+order.getStr("suppRefundNo");//商户退款单号
        reStr+=",`"+NumberUtil.mul(order.getInt("refundAmount"),0.01);//退款金额
        reStr+=",`0.00";//企业红包退款金额
        if(order.getStr("paystatus").equals("REFUND")){
            reStr+=",`ORIGINAL";//退款类型
            reStr+=",`SUCCESS";//退款状态
        }else{
            reStr+=",`";//退款类型
            reStr+=",`";//退款状态
        }
        reStr+=",`本地微信测试1";//商品名称
        reStr+=",`本地微信测试2";//商户数据包
        reStr+=",`"+NumberUtil.mul(order.getInt("feeAmount"),0.01);//手续费
        reStr+=",`"+NumberUtil.mul(order.getInt("fee"),0.1)+"%";//费率
        reStr+="\r\n";
        return reStr;
    }
}

